package org.soc.timesheet.custom.interceptor;

import java.lang.reflect.Field;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.apache.commons.lang3.RandomStringUtils;


/**
 * Intercetta i metodi che settano le pk nelle varie classi con annotation GeneratedValue=AUTO e tipo diverso da un NUMBER
 * @author edoardo
 *
 */
public aspect SetIdAutoDomainInterceptor {
	
	pointcut save() : within(org.soc.timesheet.server.domain.service.*) && execution(void save*(..));
	
	before() : save() {
		Object entity = thisJoinPoint.getArgs()[0];
		//verifico se l'entitt ha un campo annotato con Id e GeneratedValue impostato ad AUTO
		Field[] fields = entity.getClass().getDeclaredFields();
		for (Field field : fields) {
			boolean isID  = field.isAnnotationPresent(Id.class) && field.isAnnotationPresent(GeneratedValue.class);
			if(isID){
				GeneratedValue value = field.getAnnotation(GeneratedValue.class);
				switch(value.strategy()){
				case AUTO:
					if(field.getType().equals(String.class)){
						int length = ((Column)field.getAnnotation(Column.class)).length();
						field.setAccessible(true);
						try {
							field.set(entity, RandomStringUtils.randomAlphanumeric(length));
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					break;
				default:
					break;
				}
			}
			
		}
				
	}

}
